package cn.xuchunh.campusbbs.ui.fragments;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.adapter.TopicReplyPagerAdapter;
import cn.xuchunh.campusbbs.base.BaseFragment;
import cn.xuchunh.campusbbs.bean.Reply;
import cn.xuchunh.campusbbs.bean.Topic;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.net.SimpleXJsonListener;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;
import cn.xuchunh.campusbbs.utils.JsonKey;
import cn.xuchunh.campusbbs.utils.JsonParser;

/**
 *
 * Created by XuChunH on 2015/10/30.
 */
public class TopicReplyPagerFragment extends BaseFragment implements ViewPager.OnPageChangeListener {

    public static final String TAG = TopicReplyPagerFragment.class.getSimpleName();

    private Topic topic;
    private int currentItem;
    private TopicReplyPagerAdapter adapter;
    private int dataPage = 1;
    private AtomicBoolean loadReplyFromServer = new AtomicBoolean(false);

    public static TopicReplyPagerFragment newInstance(Topic topic, int currentItem, int dataPage) {

        Bundle args = new Bundle();
        args.putSerializable(IntentParamsKey.TOPIC, topic);
        args.putInt(IntentParamsKey.CURRENT, currentItem);
        args.putInt(IntentParamsKey.PAGE, dataPage);
        TopicReplyPagerFragment fragment = new TopicReplyPagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(View view) {
        ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        adapter = new TopicReplyPagerAdapter(getChildFragmentManager(), topic.getReplyList());
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(currentItem);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(this);

    }

    @Override
    protected void beforeInitView() {
        setContentViewRes(R.layout.fragment_topic_reply_pager);
    }

    @Override
    protected void handleArgs(Bundle args) {
        if (args != null) {
            topic = (Topic) args.getSerializable(IntentParamsKey.TOPIC);
            currentItem = args.getInt(IntentParamsKey.CURRENT, 0);
            dataPage = args.getInt(IntentParamsKey.PAGE, 1);
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (adapter.getCount() >= 10 && adapter.getCount() - 1 - position < 3 && !loadReplyFromServer.get()) {
            loadReplyFromServer.set(true);
            HttpRequestManager.getInstance(getActivity())
                    .loadTopicDetail(
                            10,
                            topic.getId(),
                            0,
                            topic.getForumId(),
                            dataPage,
                            simpleXJsonListener,
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    loadReplyFromServer.set(false);
                                }
                            },
                            TAG);
        } else {

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private SimpleXJsonListener<List<Reply>> simpleXJsonListener = new SimpleXJsonListener<List<Reply>>() {
        @Override
        public List<Reply> parseData(JSONObject jsonObject) throws Exception {
            return JsonParser.parseReplyList(jsonObject.optJSONArray(JsonKey.LIST), topic.getId());
        }

        @Override
        public void onResponse(List<Reply> response) {
            if(response != null && response.size() > 0){
                adapter.addReplyList(response);
                dataPage++;
            }
            loadReplyFromServer.set(false);
        }
    };

}
